package cn.kent.simple;

/**
 * 404. 左叶子之和
 */
public class SumOfLeftLeaves {

    /**
     * 深度优先遍历
     */
    public static int sumOfLeftLeaves(TreeNode root) {
        return root != null ? dfs(root) : 0;
    }

    private static int dfs(TreeNode root) {
        int sum = 0;
        if (root.left != null) {
            sum += isLeafNode(root.left) ? root.left.val : dfs(root.left);
        }
        if (root.right != null && !isLeafNode(root.right)) {
            sum+=dfs(root.right);
        }
        return sum;
    }

    private static boolean isLeafNode(TreeNode node) {
        return node.left == null && node.right == null;
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
